package linkednode;

public class LinkedNodeDemo {

    public static void main(String[] args) {
        LinkedNodeDemo demo = new LinkedNodeDemo();
        demo.test();
    }

    private void test() {
        Node head = initLinkedList(10);
        printLinkedList(head);
        System.out.println("******开始反转链表******");
        Node reversedHead = reverseLinkedList(head);
        printLinkedList(reversedHead);
    }

    private Node initLinkedList(int size) {
        Node<Integer> head = new Node<>(0, null);
        Node cur = head;
        for (int i = 1; i < size; i++) {
            cur.next = new Node<>(i, null);
            cur = cur.next;
        }
        return head;
    }

    private void printLinkedList(Node head) {
        Node node = head;
        while (node != null) {
            System.out.println(node.value);
            node = node.next;
        }
    }

    private Node reverseLinkedList(Node head) {
        if (head == null || head.next == null) {
            return head;
        }

        Node prev = null;
        while (head.next != null) {
            Node next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        head.next = prev;
        return head;
    }

    static class Node<T> {
        private T value;
        private Node<T> next;

        Node(T value, Node<T> next) {
            this.value = value;
            this.next = next;
        }
    }
}
